const path = require("path");
const gm = require("gm");

const matchl_source = path.join(__dirname, "./capimg/matchl.png");
const matcht_source = path.join(__dirname, "./capimg/matcht.png");
const matchr_source = path.join(__dirname, "./capimg/matchr.png");
const matchb_source = path.join(__dirname, "./capimg/matchb.png");
const block_sources = [
  path.join(__dirname, `./capimg/default0.jpg`),
  path.join(__dirname, `./capimg/default1.jpg`)
]
const match_border_source = path.join(__dirname, `./capimg/matchborder.png`);

let matchl = gm(matchl_source);
let matcht = gm(matcht_source);
let matchr = gm(matchr_source);
let matchb = gm(matchb_source);
let matchs = [matchl, matcht, matchr, matchb];

function drawCaptcha(index, raMatchIndex) {
  let x = index % 3;
  let y = (index - x) / 3;
  let block_source = block_sources[Math.floor(Math.random() * 2)];
  let block = gm(block_source).crop(250, 250, (x + 1) * 250, y * 250).setFormat("jpg")
  let match = matchs[raMatchIndex];
  let img = gm()
    .in("-page", "+0+0")
    .in(block_source)
    .in("-geometry", `220x220`)
    .in("-page", `+${15 + (x + 1) * 250}+${15 + y * 250}`)
    .in(match.source)
    .flatten()
    .setFormat("jpg");
  let matchBorder = gm(match_border_source)
    .rotate("#00000000", raMatchIndex * 90)
    .resize(220)
    .setFormat("png");
  console.log(index, raMatchIndex)
  return {
    img,
    block,
    match: match.resize(220).setFormat("png"),
    matchBorder
  };
}

module.exports = drawCaptcha;
